package p10.code;

import java.util.concurrent.CountDownLatch;

public class TestHarness {

    /**
     *
     * @param nThreads 线程数量
     * @param task 任务
     * @return
     * @throws InterruptedException
     */
    public long timeTasks(int nThreads , final Runnable task) throws InterruptedException {

        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(nThreads);

        for(int i=0;i<nThreads;i++) {
            Thread t = new Thread(() -> {
                try{
                    //所在的线程都保持等待状态
                    startGate.await();
                    try{
                        task.run();
                    }
                    finally {
                        //endGate减一操作
                        endGate.countDown();
                    }
                }catch(InterruptedException ignored){}
            });
            t.start();
        }

        long start = System.nanoTime();//记录开始时间
        Thread.sleep(10000);
        startGate.countDown();//它让创建的线程开始并发执行
        endGate.await();//它让timeTasks方法进入等待状态，直到endGate为0
        long end = System.nanoTime();//记录结束时间

        return end-start;
    }

    public static void main(String[] args) throws InterruptedException {
        TestHarness testHarness = new TestHarness();
        System.out.println(testHarness.timeTasks(10, () -> System.out.println("我是一个任务...")));
    }

}
